﻿/**
 * Yaml dotnetLib 官方参考：（不知所云，而且必须再封装一层才能用）
 * https://github.com/aaubry/YamlDotNet
 * 
 * 
 */
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization;

public enum AssetType
{
    Scene,
    Prefab,
    Others
}
public static class AssetReader
{
    public static YamlStream Load(string path)
    {
        var yamlStr = File.ReadAllText(path);
        var input = new StringReader(yamlStr);
        var yaml = new YamlStream();
        yaml.Load(input);
        return yaml;
    }
    // Start is called before the first frame update
    public static AssetYamlBase LoadYaml(string path)
    {
        string extension = Path.GetExtension(path);
        AssetType yamlType ;
        if (extension == ".unity")
        {
            yamlType = AssetType.Scene;
        }
        else if (extension == ".prefab")
        {
            yamlType = AssetType.Prefab;
        }
        else
        {
            yamlType = AssetType.Others;
        }
        var yamlStr = File.ReadAllText(path);
        var input = new StringReader(yamlStr);
        var yaml = new YamlStream();
        yaml.Load(input);
        
        var mapping =
            (YamlMappingNode)yaml.Documents[0].RootNode;
        string gameObjectId = "";
        //string name = "";
  
        foreach (var entry in mapping.Children)
        {
          //  name = entry.Key.ToString();//gameobject能通过这个方法获取，其他则不可以
            Debug.Log("value:"+((YamlScalarNode)entry.Key).Value);
            dumpExcusive(entry.Value);
            //YamlNode node = entry.Value;
            //YamlMappingNode mappingNode = entry.Value as YamlMappingNode;
            //string s = mappingNode.Children[new YamlScalarNode("m_RootGameObject")].ToString();
            //Debug.Log(s);

            //这个才是prefab节点？？？？
            gameObjectId = GetPrefabGameObjectId(entry.Value);
            Debug.LogWarning("print Prefab:" + gameObjectId);
        }

        AssetSetting lightMapSet = null;
        //遍历每个节点，分析文档结构
        foreach (var node in yaml.Documents)
        {
            //string nodeName = node.RootNode.ToString();//没用，这是所有字串的输出
            //Debug.Log(node.RootNode);
            var obj = GetInstance(node.RootNode);
            string nodeName = obj.Name;
            if (nodeName == "LightmapSettings")
            {
                var mapDataAsset = obj.Children[new YamlScalarNode("m_LightingDataAsset")];

                lightMapSet = new AssetSetting();
                var asset = mapDataAsset.GetValueAssetYamlBase();
                lightMapSet.FileId = asset.FileId;
                lightMapSet.Guid = asset.Guid;
                //lightMapSet.FileId = mapDataAsset.
                Debug.Log("lit map file id=" + lightMapSet.FileId);


            }
        }
        
        if (yamlType == AssetType.Scene)
        {
            AssetScene scene = new AssetScene();
            scene.LightMapSetting = lightMapSet;
            Debug.Log("scene get light map =" + lightMapSet.FileId);
            var node = Find(yaml, lightMapSet.FileId);
            return scene;
        }
        else
        {
            return null;

        }


    }
    public static YamlStream Set(YamlStream yaml, int index, string key, string value)
    {
        var doc = yaml.Documents[index];
        var serializer = new SerializerBuilder().Build();
        YamlMappingNode node = doc.RootNode as YamlMappingNode;
        var litmap = node.Children[new YamlScalarNode("m_LightingDataAsset")] as YamlMappingNode;
        litmap.Children.Clear();
        YamlScalarNode empty_fileId = new YamlScalarNode("fileID");
        empty_fileId.Value = "0";
        litmap.Children.Add(new YamlScalarNode("fileID"),empty_fileId);
        
        
        return yaml;
    }
    [System.Obsolete("遍历整个yaml文件，暂时无用")]
    /// <summary>
    /// 
    /// </summary>
    /// <param name="yaml"></param>
    /// <param name="fileId"></param>
    /// <returns></returns>
    static YamlNode Find(YamlStream yaml, string fileId)
    {
        foreach (var doc in yaml.Documents)
        {
            //var bb = Parse(doc);
            //if (bb.FileId == fileId)
            //{
            //    return bb.Node;
            //}
        }

        return null;
    }
    /// <summary>
    /// 专门for yamldoc的方法；基础方法还是那个方法
    /// </summary>
    /// <param name="doc"></param>
    /// <returns></returns>
    static AssetYamlBase Parse(YamlDocument doc)
    {
        YamlMappingNode map = doc.RootNode as YamlMappingNode;
        return map.GetValueAssetYamlBase();
    }

    static YamlObject GetInstance(YamlNode node)
    {
        YamlMappingNode n = node as YamlMappingNode;
        foreach (var v in n.Children)
        {
            YamlObject obj = new YamlObject();
            obj.Name = v.Key.ToString();
            obj.Node = v.Value;
            var map = v.Value as YamlMappingNode;
            obj.Children = map.Children;
            return obj;
        }

        return null;
    }
    static string GetKey(YamlNode node)
    {
        YamlMappingNode n = node as YamlMappingNode;
        foreach (var v in n.Children)
        {
            return v.Key.ToString();
        }

        return "";
    }
    static string GetPrefabGameObjectId(YamlNode node_prefab)
    {
        YamlMappingNode map_prefab = node_prefab as YamlMappingNode;
        if (map_prefab.Children.ContainsKey(new YamlScalarNode("m_RootGameObject")) == false)
        {
            return "NULL";
        }
        var item = map_prefab.Children[new YamlScalarNode("m_RootGameObject")];
        YamlMappingNode map_item = item as YamlMappingNode;
        string fileId = "";
        //TODO:暂时不知道怎么取第一个节点
        foreach (var k_v in map_item.Children)
        {
            //取一个简单值，绕晕你，再绕晕你。。。。就问你服不服
            fileId = ((YamlScalarNode)k_v.Value).Value;
            break;
        }
        return fileId;
    }
    static void dumpExcusive(YamlNode node, int index = 0)
    {
        YamlMappingNode mapping = node as YamlMappingNode;
        if (mapping == null)
        {
            YamlScalarNode mScalar = node as YamlScalarNode;
            if (mScalar == null)
            {
                YamlSequenceNode mSequence = node as YamlSequenceNode;
                if (mSequence != null)
                {
                    Debug.Log("无法获得数组" + "----:" + index);
                }
                else
                {
                    Debug.Log("是数组" + "----:" + index);
                }
            }
            else
            {
           
                Debug.Log(mScalar.Tag+":"+mScalar.Value + ":" + index);
            }
            return;
        }
        foreach (var entry in mapping)
        {
            YamlScalarNode v = entry.Value as YamlScalarNode;
            if (v == null)
            {
                Debug.Log(((YamlScalarNode)entry.Key).Value + ":(not text):" + index);
            }
            else
            {
                Debug.Log(((YamlScalarNode)entry.Key).Value + ":" + v.Value + ":" + index);
            }
            //var scalar = ((YamlScalarNode) entry.Key).Value;
       
            YamlMappingNode mappingNode = entry.Value as YamlMappingNode;
            if (mappingNode != null)
            {

                foreach (var child in mappingNode)
                {
                    dumpExcusive(child.Value, index+1);
                }
            }
        }
    }

}
